package com.mes.handler;

import com.basis.utils.BaseServletHandler;
import com.basis.utils.CodeGenerateRuleUtil;
import com.mes.data.EmesPBomItem;
import com.mes.data.EmesProcessRoute;
import com.mes.manufacture.data.EmesoManuOrder;
import com.mes.plan.data.EmesPlanOrder;
import com.mes.utils.ReturnSheetUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.dal.service.OBDal;
import org.openbravo.dal.service.OBQuery;
import org.openbravo.model.common.plm.Product;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PlanOrderImportHandler extends BaseServletHandler {

	public static final String POSITIVE_INTEGER = "^\\d*[1-9]\\d*$";
	public static final String IS_NOT_NULL = "ISNOTNULL";
	public static final String IS_NUMBER = "ISNUMBER";
	private Pattern p = Pattern.compile(POSITIVE_INTEGER);
	private Matcher m;

	@Override
	protected JSONObject service(HttpServletRequest request, HttpServletResponse response) {

		JSONObject result = ReturnSheetUtils.getSheet(request, response);
		JSONObject jsonRep = new JSONObject();

		// 新建计划订单ID
		String head_ID = request.getParameter("DataId");

		String message = "";
		// 获取新建计划订单
		EmesPlanOrder epo = OBDal.getInstance().get(EmesPlanOrder.class, head_ID);

		try {

//			if (epo.getStatus().equalsIgnoreCase("CREATE")) {
//				jsonRep.put("desc", "计划订单不为创建状态，无法导入。");
//				jsonRep.put("result", false);
//				return jsonRep;
//			}

			Sheet sheet;
			sheet = (Sheet) result.get("sheet");
			if (result.getBoolean("flag")) {
				// 获取最后一行
				int lastLine = sheet.getLastRowNum();
				JSONObject obj = new JSONObject();
				for (int i = 1; i <= lastLine; i++) {
					obj = insertPlanOrderData(sheet.getRow(i), epo);
					if (!obj.getBoolean("flag")) {
						message += obj.getString("message");
						continue;
					}
				}
				if ("".equalsIgnoreCase(message)) {
					epo.setStatus("WAIT");
					OBDal.getInstance().save(epo);
					OBDal.getInstance().commitAndClose();
					jsonRep.put("desc", "导入成功，一共导入：" + lastLine + "条数据。");
					jsonRep.put("result", true);
					return jsonRep;
				} else {
					jsonRep.put("desc", message);
					jsonRep.put("result", false);
					OBDal.getInstance().rollbackAndClose();
					return jsonRep;
				}
			} else {
				OBDal.getInstance().rollbackAndClose();
				jsonRep.put("desc", "导入失败。");
				jsonRep.put("result", false);
				return jsonRep;
			}
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();

		}
		return null;
	}

	/**
	 * 插入数据库
	 * 
	 * @param row
	 * @return
	 * @throws Exception
	 */
	protected JSONObject insertPlanOrderData(Row row, EmesPlanOrder epo) throws Exception {

		JSONObject result = new JSONObject();
		// 初始正确
		result.put("flag", true);

		// 生产订单产品
		Product product = null;
		// 生产订单的产品
		EmesProcessRoute process = null;
		// 生产订单所在的BOM结构
		EmesPBomItem bomItem = null;

		String message = "";
		String materialCode = ReturnSheetUtils.readValue(row.getCell(1)); // 图号
		String qty = ReturnSheetUtils.readValue(row.getCell(3)); // 一台的总数量

		// 验证物料是否存在
		if (!"".equalsIgnoreCase(materialCode)) {
			product = getProduct(materialCode);
			if (product == null) {
				result.put("flag", false);
				result.put("message", "图号为:" + materialCode + "的物料不存在，请仔细检查。</br>");
				return result;
			}
		} else {
			result.put("flag", false);
			result.put("message", row.getRowNum() + "图号不能为空，请仔细检查。</br>");
			return result;
		}

		// 数值是否正确
		if (!"".equalsIgnoreCase(qty)) {
			boolean flag = isValidator(qty, IS_NUMBER);
			if (!flag) {
				result.put("flag", false);
				result.put("message", "图号为:" + materialCode + "的数量值不正确，请仔细检查。</br>");
				return result;
			}
		} else {
			result.put("flag", false);
			result.put("message", row.getRowNum() + "数量不能为空，请仔细检查。</br>");
			return result;
		}
		try {
			process = getProcessRoute(product.getId());
			bomItem = getEmesPBomItem(product.getId());
			if (bomItem == null) {
				result.put("flag", false);
				result.put("message", row.getRowNum() + "并未在默认的bom结构中找到，请仔细检查。");
				return result;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		// 插入生产订单数据
		insertEmesMaunOrder(product, epo, Long.valueOf(qty), process, bomItem);

		return result;
	}

	/**
	 * 验证是数字
	 * 
	 * @param value
	 * @return
	 */

	public boolean isValidator(String value, String type) {

		if (type.equalsIgnoreCase(IS_NOT_NULL)) {
			return false;
		} else if (type.equalsIgnoreCase(IS_NUMBER)) {
			m = p.matcher(value.trim());
			if (m.matches()) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}

	/**
	 * 获取物料
	 */
	public Product getProduct(String value) {
		OBQuery query = OBDal.getInstance().createQuery(Product.class, " as mp where mp.searchKey = :value");
		query.setNamedParameter("value", value);
		return (Product) query.uniqueResult();
	}

	/**
	 * 获取工艺路线
	 * 
	 * @return
	 */
	public EmesProcessRoute getProcessRoute(String value) {
		OBQuery query = OBDal
						.getInstance()
						.createQuery(EmesProcessRoute.class,
										" as e where e.product.id = :value and e.validate is true and e.audited = 'Y' and e.default = 'Y'");
		query.setNamedParameter("value", value);
		return (EmesProcessRoute) query.uniqueResult();
	}

	/**
	 * 获取所在工艺BOM结构
	 * 
	 * @return
	 */
	public EmesPBomItem getEmesPBomItem(String value) {
		OBQuery query = OBDal
						.getInstance()
						.createQuery(EmesPBomItem.class,
										" as e where e.product.id = :value and e.emesPbom.default is true and e.emesPbom.isaudit is true");
		query.setNamedParameter("value", value);
		return (EmesPBomItem) query.uniqueResult();
	}

	/**
	 * 插入生产订单表
	 * @return
	 */
	protected void insertEmesMaunOrder(Product product, EmesPlanOrder epo, Long qty, EmesProcessRoute process,
					EmesPBomItem bomItem) {
		EmesoManuOrder emo = new EmesoManuOrder();
		emo.setEmespPlanorder(epo);
		emo.setProduct(product);
		emo.setQty(new BigDecimal(epo.getQty()).multiply(new BigDecimal(qty)));
		emo.setName(product.getName());
		emo.setOrganization(bomItem.getOrganization());
		// 获取生产订单编码
		String code = CodeGenerateRuleUtil.getCode("2CB793C1EE864E87BB01B8D2BACBBAE6", "Code");
		emo.setCode(code);
		emo.setEmesProcessRoute(process);
		emo.setUom(product.getUOM());
		emo.setEmesPbom(bomItem.getEmesPbom());
		emo.setAudit(false);
		//生产订单时间
		emo.setDatePlaned(epo.getPlanedDateFrom());
		emo.setDateDone(epo.getPlanedDateTo());
		OBDal.getInstance().save(emo);
	}

}
